// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.FBAInventory;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.FBAInventoryMapper;
import com.fowo.api.model.fbainventory.FBAInventoryItemVo;
import com.fowo.api.model.fbainventory.FBAInventoryItemVo;
import com.fowo.api.model.fbainventory.FBAInventorySearchParamPo;
import com.fowo.api.model.fbainventory.FBAInventorySearchParamPo;
import com.fowo.api.model.fbainventory.FBAInventorySyncDataAction;
import com.fowo.api.model.fbainventory.FBAInventoryVo;
import com.fowo.api.service.FBAInventoryService;
import com.fowo.api.service.impl.FBAInventoryServiceImpl;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * FBA库存 服务实现类
 * @author 蜂窝蜜造平台 配置人：汤帅杰，任凯
 */
@Service
@Slf4j
@DataObjectType(FBAInventory.class)
@DS("ds24")
public class FBAInventoryServiceImpl
  extends ServiceImpl<FBAInventoryMapper, FBAInventory>
  implements FBAInventoryService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
      put("productIdName", "p.`name`");
      put("headName", "su.`name`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected FBAInventoryService self;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected FBAInventorySyncDataAction fBAInventorySyncDataAction;

  @Resource
  protected Validator validator;

  /**
   * 创建FBA库存
   * @param model FBA库存
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(FBAInventoryVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInventory entity = new FBAInventory();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("FBA库存保存失败");
  }

  /**
   * 更新FBA库存
   * @param model FBA库存
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(FBAInventoryVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInventory entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("FBA库存不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "day270"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新FBA库存（带空值）
   * @param model FBA库存
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(FBAInventoryVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    FBAInventory entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("FBA库存不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(FBAInventory::getSid, model.getSid())
      .set(FBAInventory::getListingId, model.getListingId())
      .set(FBAInventory::getWarehouse, model.getWarehouse())
      .set(FBAInventory::getLastUpdateTime, model.getLastUpdateTime())
      .set(FBAInventory::getLastUpdateUser, model.getLastUpdateUser())
      .set(
        model.getPicture() != null,
        FBAInventory::getPicture,
        JSON.toJSONString(model.getPicture())
      )
      .setSql(model.getPicture() == null, "picture = null")
      .set(FBAInventory::getAsin, model.getAsin())
      .set(FBAInventory::getMsku, model.getMsku())
      .set(FBAInventory::getFnsku, model.getFnsku())
      .set(FBAInventory::getProductId, model.getProductId())
      .set(FBAInventory::getSku, model.getSku())
      .set(
        model.getHead() != null,
        FBAInventory::getHead,
        JSON.toJSONString(model.getHead())
      )
      .setSql(model.getHead() == null, "head = null")
      .set(FBAInventory::getTotalInventory, model.getTotalInventory())
      .set(FBAInventory::getAvailableStock, model.getAvailableStock())
      .set(FBAInventory::getFbaAvailableForSale, model.getFbaAvailableForSale())
      .set(FBAInventory::getFbmAvailableForSale, model.getFbmAvailableForSale())
      .set(
        FBAInventory::getWarehouseToBeAdjusted,
        model.getWarehouseToBeAdjusted()
      )
      .set(
        FBAInventory::getDuringWarehouseAdjustment,
        model.getDuringWarehouseAdjustment()
      )
      .set(FBAInventory::getToBeShipped, model.getToBeShipped())
      .set(FBAInventory::getPlannedWarehousing, model.getPlannedWarehousing())
      .set(FBAInventory::getStandardInTransit, model.getStandardInTransit())
      .set(FBAInventory::getActualInTransit, model.getActualInTransit())
      .set(FBAInventory::getInStorage, model.getInStorage())
      .set(FBAInventory::getNotAvailableForSale, model.getNotAvailableForSale())
      .set(FBAInventory::getUnderInvestigation, model.getUnderInvestigation())
      .set(FBAInventory::getWarningStatus, model.getWarningStatus())
      .set(FBAInventory::getDay30, model.getDay30())
      .set(FBAInventory::getDay60, model.getDay60())
      .set(FBAInventory::getDay90, model.getDay90())
      .set(FBAInventory::getDay180, model.getDay180())
      .set(FBAInventory::getDay365, model.getDay365())
      .set(FBAInventory::getDay366, model.getDay366())
      .set(
        FBAInventory::getFulfillmentChannelType,
        model.getFulfillmentChannelType()
      )
      .eq(FBAInventory::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(FBAInventorySearchParamPo search) {
    return false;
  }

  /**
   * 删除FBA库存
   * @param id FBA库存的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除FBA库存
   * @param ids FBA库存的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过仓库查询FBA库存主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByWarehouse(Long warehouse) {
    return this.baseMapper.getIdByWarehouse(warehouse);
  }

  /**
   * 通过仓库查询FBA库存多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByWarehouse(List<Long> list) {
    return this.baseMapper.getIdsByWarehouse(list);
  }

  /**
   * 通过FBA库存主键查询仓库
   */
  @Override
  public Long getWarehouseById(Long id) {
    return this.baseMapper.getWarehouseById(id);
  }

  /**
   * 通过FBA库存主键查询仓库列表
   */
  @Override
  public List<Long> getWarehouseByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getWarehouseByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (Long) stringObjectMap.get("warehouse"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id FBA库存的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public FBAInventoryVo getVoById(Long id) throws Exception {
    FBAInventoryVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询FBA库存
   * @param search 查询条件
   * @return FBA库存分页查询结果
   */
  @Override
  public Page<FBAInventoryItemVo> pageSearch(FBAInventorySearchParamPo search) {
    Page<FBAInventoryItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(FBAInventoryItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * FBA库存快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'FBAInventoryOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<FBAInventoryItemVo>> searchOptions(
    FBAInventorySearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询FBA库存
   * @param search 查询条件
   * @return FBA库存列表查询结果
   */
  @Override
  public List<FBAInventoryItemVo> search(FBAInventorySearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询FBA库存最后更新时间
   * @param search 查询条件
   * @return FBA库存最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(FBAInventorySearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 同步数据
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步数据操作"
  )
  @Override
  public void syncData() throws Exception {
    if (fBAInventorySyncDataAction == null) {
      throw new Exception("此操作当前不可用");
    }
    fBAInventorySyncDataAction.run();
  }

  /**
   * FBA库存
   */
  @Override
  public List<FBAInventoryItemVo> fBAInventory(
    FBAInventorySearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", FBAInventoryServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.fBAInventory(search);
  }

  /**
   * FBA库存分页
   */
  @Override
  public Page<FBAInventoryItemVo> fBAInventoryPage(
    FBAInventorySearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", FBAInventoryServiceImpl.SORT_FIELD_MAP);
    return this.baseMapper.fBAInventoryPage(search.toPage(), search);
  }

  /**
   * FBA库存最后更新时间
   */
  @Override
  public Date fBAInventoryLastUpdateTime(FBAInventorySearchParamPo search) {
    return this.baseMapper.fBAInventoryLastUpdateTime(search);
  }
}
